<template>
  <div class="">
    <img
      :src="defaultLoadingImg"
      :data-url="item.url"
      v-for="(item, index) in imageList"
      :key="index"
      ref="lazyImage1"
    />
  </div>
</template>

<script>
import defaultLoadingImg from "./components/1.gif";
export default {
  props: {},
  components: {},
  data() {
    return {
      defaultLoadingImg,
      imageList: [
        {
          url: "https://spaice-cdn.ventmere.cn/files/R_photo/0/2022/12/19/49a3be2c5ec34d33848a18280922c1d1/f34ff613-6548-4fd9-8a0f-e8018b54ac6b.jpg",
        },
        {
          url: "https://spaice-cdn.ventmere.cn/files/R_photo/0/2022/12/19/9a4c99d9a31d42859b09112637f9afff/adce327e-99c5-41d7-bc2c-1665f62b3c9a.jpg",
        },
        {
          url: "https://spaice-cdn.ventmere.cn/files/R_photo/0/2022/12/19/ad679be766494e66aa8e6477ab183cfb/60257009-b063-4e1a-a96d-39ca5f067070.jpg",
        },
        {
          url: "https://spaice-cdn.ventmere.cn/files/R_photo/0/2022/12/12/5f0a146c2ea7454d9a9ff888a438aeda/ea542c88-c267-4499-aa96-ec34754af02f.jpg",
        },
        {
          url: "https://spaice-cdn.ventmere.cn/files/R_photo/0/2022/12/5/45f6eeba39944ecf968d4fbd1c87e32a/942ba75b-5e25-4544-bad4-556291f0b2f5.jpg",
        },
      ],
    };
  },
  created() {},
  mounted() {
    this.initDataFun(); // 初始化数据
  },
  beforeDestroy() {},
  computed: {},
  watch: {},
  methods: {
    // 初始化数据
    initDataFun() {
      const imgs = this.$refs.lazyImage1;
      scrollFn();
      // 监听滚动事件
      window.onscroll = scrollFn;
      function scrollFn() {
        const clietH =
          window.innerHeight ||
          document.documentElement.clientHeight ||
          document.body.clientHeight;
        const scrollTop =
          document.documentElement.scrollTop ||
          window.pageYOffset ||
          document.body.scrollTop;
        console.log(clietH, scrollTop);
        Array.from(imgs).forEach((item) => {
          let eleTop = item.offsetTop;
          // console.log(eleTop)
          let count = scrollTop + clietH - eleTop;
          console.log(count);
          // 可设置为>100 查看懒加载效果
          if (count > 100) {
            //从data-url中取出真实的图片地址赋值给scr
            item.setAttribute("src", item.getAttribute("data-url"));
          }
        });
      }
    },
  },
};
</script>

<style lang="less"></style>

<style lang="less" scoped>
img {
  margin-top: 200px;
  width: 250px;
  display: block;
}
</style>
